package com.tedu.day08springmvc.controller;

import com.tedu.day08springmvc.mapper.UserMapper;
import com.tedu.day08springmvc.pojo.dto.UserDTO;
import com.tedu.day08springmvc.pojo.entity.User;
import com.tedu.day08springmvc.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Controller
@RestController //使用@RestController注解，表示该类中所有方法默认为@ResponseBady注解方法，不需再在方法上单独定义
public class UserController {
    @Autowired
    private UserMapper userMapper;

    //@RequestMapping(value="/users/reg",method=RequestMethod.POST)
    @PostMapping("/users/reg")
    //@ResponseBody
    public String reg(UserDTO userDTO){
        System.out.println(userDTO);
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        System.out.println(user);
        user.setCreated(new Date());
        int num = userMapper.insertUser(user);
        System.out.println(num>0?"success":"fail");
        return "Congratulations,regSuccess!";
    }
    //@RequestMapping(value="/users/update",method=RequestMethod.PUT)
    @PutMapping("/users/update")
    //@ResponseBody
    public String  update(UserDTO userDTO){
        System.out.println(userDTO);
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        System.out.println(user);
        int num=userMapper.updateUser(user);
        return num>0?"updateSuccess!":"updateFail!";
    }
    //@RequestMapping(value="/users/delete",method=RequestMethod.DELETE)
    @DeleteMapping("/users/delete/{id}")
    //@ResponseBody
    public String delete(@PathVariable int id){ //@PathVariable 表示参数是从路径中获取
        int num = userMapper.deleteUser(id);
        return num>0?"deleteSuccess!":"deleteFail!";
    }
    //@RequestMapping(value="/users/find",method= RequestMethod.GET)
    @GetMapping("/users/find")
    //@ResponseBody
    public List<UserVO> find(){
        return userMapper.selectUser();
    }

}
